# == Schema Information
#
# Table name: stores
#
#  id          :integer          not null, primary key
#  name        :string           not null
#  code        :string           not null
#  contact     :string
#  phone       :string
#  address     :string
#  product_ids :text             default([]), is an Array
#  account_id  :integer          not null
#  region_id   :integer          not null
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#  user_id     :integer
#  rate        :integer          default(0)
#

class Store < ActiveRecord::Base

	belongs_to :account
	belongs_to :region
	belongs_to :user
  has_many :region_strategies

	#validates_uniqueness_of :user_id, message: '用户已被占用'

	before_create :gen_code

	def gen_code
		self.code = 'ST' << SecureRandom.hex(2)
	end

	def proeducts_hash
		Product.in(id: product_ids).map(&:to_hash)
	end

	def to_hash
		attributes.merge(
			user_name: 		user.try(:name), 
			user_mobile: 	user.try(:mobile), 
			region_name: 	region.name
		)
	end

	def select_hash
		{
			id: id,
			name: name
		}
	end

  def full_name
    self.region.try(:name) + self.name
  end

end
